package com.erp.dao.impl;

import com.erp.bean.Entrepot;
import com.erp.dao.EntrepotDao;
import com.erp.util.db.DataBaseDao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lyb
 * 创建仓库数据访问实现类
 */
public class EntrepotDaoImpl extends DataBaseDao implements EntrepotDao {
    @Override
    public List<Entrepot> findAll() {
        List<Entrepot> list=new ArrayList<>();
        Entrepot entrepot=null;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql="select entid,entname,loc from entrepot";
            pstmt=conn.prepareStatement(sql);
            rs= pstmt.executeQuery();
            while (rs.next()){
                entrepot=new Entrepot(rs.getInt(1),rs.getString(2),rs.getString(3));
                list.add(entrepot);
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }
        return list;
    }

    @Override
    public Entrepot findByentid(int entid) {
        Entrepot entrepot=null;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql="select entid,entname,loc from entrepot where entid=? ";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1,entid);
            rs= pstmt.executeQuery();
            while (rs.next()){
                entrepot=new Entrepot(rs.getInt(1),rs.getString(2),rs.getString(3));}

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }
        return entrepot;
    }

    @Override
    public int update(Entrepot entrepot) {
        int i=0;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql="update entrepot set entid=?,entname=?,loc=? where entid=?";
            //创建预编译指令
            pstmt=conn.prepareStatement(sql);
            //设置参数
            pstmt.setInt(1,entrepot.getEntid());
            pstmt.setString(2,entrepot.getEntname());
            pstmt.setString(3,entrepot.getLoc());
            pstmt.setInt(4,entrepot.getEntid());
            //获得结果
            i=pstmt.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }

        return i;
    }

    @Override
    public int add(Entrepot entrepot) {
        int i=0;
        //创建sql语句
        try {
            //获取数据库连接对象
            buildConnection();
            String sql="insert into entrepot (entname,loc) values(?,?)";
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,entrepot.getEntname());
            pstmt.setString(2,entrepot.getLoc());
            //获取结果
            i=pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }
        return i;
    }
}
